<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="React"></div>

<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<!-- jsx转为js -->
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

<script type="text/babel">

    /**
     * 挂载 mount    一个组件放到页面
     * 卸载 unmount  一个组件移除了
     *
     * 生命周期回调函数，  也可以叫生命周期钩子函数， 还可以叫 生命周期函数，还可以叫 生命周期钩子
     */
    class Life extends React.Component {

        state = {opacity: 1}

        timer

        death = () => {
            // 卸载组件
            ReactDOM.unmountComponentAtNode(document.getElementById("React"))

        };

        // 组件挂载完毕调用，只调用一次
        componentDidMount() {
            this.timer = setInterval(() => {
                let {opacity} = this.state
                opacity -= 0.1
                this.setState({opacity: opacity})
                if (opacity <= 0) {
                    this.setState({opacity: 1})
                }
            }, 200)
        }

        // 组件将要卸载
        componentWillUnmount() {
            clearInterval(this.timer)
        }

        // render调用的时机：初始化渲染、状态更新之后
        render() {
            return (
                    <div>
                        <h2 style={{opacity: this.state.opacity}}>React生命周期</h2>
                        <button onClick={this.death}>不活了</button>
                    </div>
            )
        }
    }

    ReactDOM.render(<Life/>, document.getElementById("React"))
</script>
</body>
</html>